package 
{
    import com.bit101.components.Label;
    import com.bit101.components.PushButton;
    import flash.display.Loader;
    import flash.display.LoaderInfo;
    import flash.display.Sprite;
    import flash.events.*;
    import flash.net.*;
    import flash.net.URLRequest;
    import mge.Utils;
	
	/**
	 * ...
	 * @author ivan
     * 
     * For 15 minutes reading with coffee:
     * http://www.adobe.com/devnet/actionscript/articles/event_handling_as3.html
	 */
	public class SharedEventsParent extends Sprite 
	{
		//[Embed("c:/prj/flash/separent/bin/chrono.swf")]
        //private var CoolAnimationAsset:Class;

		public function SharedEventsParent():void 
		{
            ///
            /// URLLoader world: dynamic loaded content, no need to link with.
            /// pros: Faster compile times, modular design.
            /// cons: Wait times executing application.
            ///
			var loader:Loader = new Loader();
            loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoadCompleted);
            var url:URLRequest = new URLRequest("SharedEventsChild.swf");
            loader.load(url);
            loader.name = "MyChild";
            addChild(loader);
            
            trace("Parent created");
            addEventListener("SharedEvent", onSharedEvent, true); // This is getted on capture phase
            addEventListener("SharedEvent", onSharedEvent);       // This other on bubble phase.
            
            new PushButton(this, 10, 10, "ParentEvent", onPush);
		}
        
        private function onPush(e:Event):void
        {
            var event:SharedEvent = new SharedEvent("SharedEvent", true);
            this.getChildByName("MyChild").dispatchEvent(event);
        }
        
        private function onSharedEvent(e:Event):void
        {
            trace("Parent: Event received!");
        }
        
        /*
         * public functions can be called from a child movieclip coming from an external source.
         * */
        public function notification(msg:String):void
        {
            new Label(this, 10, 10, "Received: " + msg);
        }
        
        private function onLoadCompleted(e:Event):void
        {
            var loaderInfo:LoaderInfo = e.target as LoaderInfo;
            var swf:Object = loaderInfo.content;
            
            /*
             * public functions of the loaded movieclip can be called dinamically.
             * In this case the condig() method of chrono.swf is called.
             * chrono.swf can also call notification() this way:
             * (stage.getChildAt(0) as Object).notification("Hello!");
             * // TODO It could be accessed by name too but I don't know how.
             * */
            // (swf as Object).config("Sector 15");
           
            
             Utils.traceHierarchy2(stage);
        }
        
	}
	
}